<template>
  <div class="app-container">
    <h4 class="form-header h4">平台信息</h4>
    <div  class="rightBtn" :style="{ 'text-align': 'left' }">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
      >添加平台
      </el-button>
    </div>
    <el-table v-loading="platformLoading" :row-key="getRowKey" @row-click="clickRow" ref="table" :data="gpsList">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台名称" align="center" prop="plaformName"/>
      <el-table-column label="域名" align="center" prop="domainName"/>
      <el-table-column label="操作" width="200">
        <template v-slot:default="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            :disabled="scope.row.id==1"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.id==1"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <h4 class="form-header h4">账号信息</h4>
    <div  class="rightBtn" :style="{ 'text-align': 'left' }">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAddGPS"
      >添加账号
      </el-button>
    </div>
    <el-table v-loading="gpsAccountLoading" :row-key="getRowKey" @row-click="clickRow" ref="table" :data="peopleList">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属平台" align="center" prop="plaformName"/>
      <el-table-column label="账号" align="center" prop="userName"/>
      <el-table-column label="密码" align="center" prop="gpsPassword"/>
      <el-table-column label="操作" width="200">
        <template v-slot:default="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            v-if="scope.row.carId==vehicleId"
            @click="handleUpdateGPS(scope.row)"
            v-hasPermi="['merchant:goods:edit']"
          >修改
          </el-button>
          <el-tooltip class="item" effect="dark"
                      :content="platformGpsId==scope.row.id?'该GPS账号已经被绑定，无法继续绑定':'当前登录用户绑定GPS账号'"
                      placement="top">
            <el-button
              size="mini"
              type="text"
              :disabled="platformGpsId==scope.row.id"
              icon="el-icon-help"
              @click="handleChose(scope.row)"
            >绑定
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark"
                      content="当前用户正在使用GPS账号，无法删除"
                      :disabled="platformGpsId!=scope.row.id"
                      placement="top">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="platformGpsId==scope.row.id"
            @click="handleGPSDelete(scope.row)"
          >删除</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-form ref="form" :model="form" label-width="80px" v-if="false">
      <el-row>
        <el-col :span="5" >
          <el-form-item label="平台名称" prop="nickName">
            <el-input v-model="name" disabled readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="5" >
          <el-form-item label="域名" prop="userName">
            <el-input v-model="carnum" disabled readonly/>
          </el-form-item>
        </el-col>
<!--      </el-row>-->
<!--      <el-row>-->
        <el-col :span="5" >
          <el-form-item label="登录账号" prop="nickName">
            <el-input v-model="form.gpsUserName"/>
          </el-form-item>
        </el-col>
        <el-col :span="5" >
          <el-form-item label="登录密码" prop="userName">
            <el-input v-model="form.gpsPassword" type="password" show-password/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">

      </el-form-item>
    </el-form>

    <h4 class="form-header h4">GPS信息

    </h4>
    <!--    <el-tooltip class="item" effect="dark" content="当前GPS选择“修改/绑定”会在车牌列出现下拉选项，在下拉选项中选中后点击“绑定”后，可以将车辆绑定当前GPS" placement="top-start">-->
    <!--      <el-icon type="el-icon-info"/>-->
    <!--    </el-tooltip>-->
    <el-table v-loading="loading" :row-key="getRowKey" @row-click="clickRow" ref="table" :data="deviceList">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="device_imei"/>
      <el-table-column label="设备名称" align="center" prop="device_name"/>
      <el-table-column label="设备绑定车牌" align="center" prop="car_number"/>
      <el-table-column label="绑定车牌" align="center" prop="carnum">
        <template slot-scope="scope">
          <el-select v-model="scope.row.carId" v-if="scope.row.isEdit" value-key="id"
                     @change="changeCarNum($event,scope.row)">
            <el-option v-for="item in notImeiCarList" :label="item.carnum" :value="item.id">
            </el-option>
          </el-select>
          <span v-else>
            {{ scope.row.carnum }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="绑定名称" align="center" prop="name">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="设备过期时间" align="center" prop="device_hire_expire_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.device_hire_expire_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot:default="scope">
          <span>
            <el-button
              type="text"
              icon="el-icon-edit"
              size="mini"
              v-if="!scope.row.isEdit"
              @click="initNotImei(scope.row)"
              v-hasPermi="['merchant:goods:edit']"
            >变更/绑定
          </el-button>
            <el-button
              type="text"
              icon="el-icon-edit"
              size="mini"
              v-else
              @click="handleBingGps(scope.row,'bind')"
              v-hasPermi="['merchant:goods:edit']"
            >绑定
          </el-button>
            <el-button
              v-if="scope.row.isEdit"
              type="text"
              icon="el-icon-edit"
              size="mini"
              @click="cancelBingGps(scope.row)"
              v-hasPermi="['merchant:goods:edit']"
            >
              取消
            </el-button>
          </span>
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            v-if="scope.row.carId&&!scope.row.isEdit"
            @click="handleBingGps(scope.row,'unbind')"
            v-hasPermi="['merchant:goods:edit']">
            解绑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList"/>
    <bing-g-p-s-car ref="bingGPSCar"></bing-g-p-s-car>
    <add-gps @update="getList" ref="addVehicle" />
    <add-person-gps @update="getPeopleList" ref="addGps" :gpsList="gpsList"  />
  </div>
</template>


<script>
import {choseGps, editGpsInfo} from "@/api/system/user";
import {microApi} from "@/api/microPatrolApi";
import {
  delGPS,
  delPlatform,
  filterCarList,
  getGpsList,
  getPersonList,
  listNotImeiCar,
  updateCar
} from "@/api/merchant/car";
import addGps from './computed/addGPS.vue'
import addPersonGps from './computed/addPerson.vue'
import bingGPSCar from "@/views/vehicle/computed/bingGPSCar.vue";
import {Message} from "element-ui";

export default {
  name: "bindGPS",
  components: {addGps, addPersonGps, bingGPSCar},
  computed: {
    platformGpsId() {
      return this.$store.getters.platformGpsId
    },
    userId() {
      return this.$store.getters.userId
    },
    x_token() {
      return this.$store.getters.getWXToken
    },
    x_url() {
      return this.$store.getters.getWXUrl
    },
    member_id() {
      return this.$store.getters.getMemberId
    }
  },
  data() {
    return {
      choseCar: null,
      notImeiCarList: [],
      // 遮罩层
      loading: true,
      platformLoading: true,
      gpsAccountLoading: true,
      name: '',
      carnum: '',
      // 分页信息
      total: 0,
      pageNum: 1,
      pageSize: 10,
      vehicleId: '',
      // 角色信息
      deviceList: [],
      gpsList: [],
      peopleList: [],
      // 用户信息
      form: {
        gpsUserName: '',
        gpsPassword: ''
      }
    };
  },
  created() {
    // 获取赋值
    if (this.$route.query) {
      console.log(this.$route)
      this.name = this.$route.query.name;
      this.carnum = this.$route.query.carnum;
      this.vehicleId = this.$route.query.id
    }
    if (this.x_token == null) {
      this.initXToken()
    } else {
      this.init()
    }
  },
  methods: {
    initXToken() {
      // 判断拿取GPS的token数据
      this.$store.dispatch("LoginWX").then(res => {
        // 初始化查询数据
        this.init()
      }).catch(res => {
        this.init()
      })
    },
    handleChose(row) {
      choseGps(row.id).then(res => {
        if (res.code == 200) {
          Message.success('绑定成功')
          this.loading = true
          this.$store.dispatch("GetInfo").then(() => {
            //刷新token访问GPS
            this.initXToken()
          })
        }
      })
    },
    changeCarNum(data, row) {
      for (let i = 0; i < this.notImeiCarList.length; i++) {
        if (data == this.notImeiCarList[i].id) {
          row.name = this.notImeiCarList[i].name
          break
        }
      }
    },
    // 初始化
    init() {
      this.getGpsList()
      this.getPeopleList()
      if (this.x_token) {
        this.getList()
      } else {
        this.loading = false
      }

    },
    /** 单击选中行数据 */
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.roleId;
    },
    getList() {
      this.loading = true
      microApi(this.x_url, {
        x_token: this.x_token,
        busiCode: 'deviceList',
        body: {
          member_id: this.member_id,
          global_status: -2,
          pageNo: this.pageNum,
          pageSize: this.pageSize
        }
      }).then(res => {
        let imei = res.data.map(item => item.device_imei)
        this.total = res.recordsTotal
        let deviceList = res.data
        // 筛当前用户所有imei对应的车辆
        filterCarList({
          imei: imei.join(',')
        }).then(filterList => {
          console.log('filterList', filterList)
          // 将绑定的imei的车辆数据赋值到设备上
          for (let i = 0; i < deviceList.length; i++) {
            for (let j = 0; j < filterList.data.length; j++) {
              if (deviceList[i].device_imei === filterList.data[j].imei) {
                deviceList[i].carnum = filterList.data[j].carnum
                deviceList[i].name = filterList.data[j].name
                deviceList[i].carId = filterList.data[j].id
                deviceList[i].isEdit = false
                if (this.vehicleId == filterList.data[j].id) {
                  Message.success("你好")
                  this.initNotImei(deviceList[i])
                }
              }
            }
          }
          this.deviceList = deviceList
          // this.deviceList = res.data
          this.$nextTick(() => {
            this.loading = false
          })
        })

      }).catch(res => {
        console.error(res)
        this.loading = false
      })
    },

    getGpsList() {
      this.platformLoading = true;
      getGpsList().then(response => {
        console.log('getGpsList', response)
        this.platformLoading = false;
        this.gpsList = response.rows
      }).catch(res => {
        console.log(res)
      });
    },

    getPeopleList() {
      this.gpsAccountLoading = true;
      getPersonList().then(response => {
        console.log('getPersonList', response)
        this.gpsAccountLoading = false;
        this.peopleList = response.rows
      }).catch(res => {
        console.log(res)
      });
      ;
    },
    handleUpdate(item) {
      this.$refs.addVehicle.open(item)
    },
    handleUpdateGPS(item) {
      this.$refs.addGps.open(item)
    },
    handleAdd() {
      this.$refs.addVehicle.open()
    },
    handleAddGPS() {
      this.$refs.addGps.open()
    },
    handleDelete(item) {
      let id = item.id || this.ids
      this.$modal.confirm('是否确认删除数据项？').then(function () {
        return delPlatform(id);
      }).then(() => {
        this.getGpsList();
        this.getPeopleList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleGPSDelete(item) {
      let id = item.id || this.ids
      this.$modal.confirm('是否确认删除数据项？').then(function () {
        return delGPS(id);
      }).then(() => {
        this.getGpsList();
        this.getPeopleList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    initNotImei(row) {
      if (this.choseCar != null) {
        Message.warning("请先当前选择的GPS设备绑定车辆或取消修改")
        return
      }

      this.choseCar = JSON.parse(JSON.stringify(row))
      row.isEdit = true
      listNotImeiCar({
        imei: row.device_imei
      }).then(res => {
        if (res.code == 200) {
          this.notImeiCarList = res.rows
        }
      })
    },
    cancelBingGps(row) {
      row.isEdit = false
      row.name = this.choseCar.name
      row.carId = this.choseCar.id
      this.choseCar = null
    },
    handleBingGps(row, flag) {
      if (flag == 'bind') {
        updateCar({
          id: row.carId,
          imei: row.device_imei
        }).then(res => {
          if (res.code == 200) {
            this.cancelBingGps(row)
            this.$nextTick(() => {
              this.init()
            })
          }
        })
      } else {
        updateCar({
          id: row.carId,
          imei: ''
        }).then(res => {
          if (res.code == 200) {
            this.$nextTick(() => {
              this.init()
            })
          }
        })
      }
    },
    submitGpsForm() {
      this.form.userId = this.userId
      editGpsInfo(this.form).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess("修改成功");
          this.init()
        }
      })
    },
    /** 关闭按钮 */
    close() {
      const obj = {path: "/vehicle/index"};
      this.$tab.closeOpenPage(obj);
    },
  },
}
</script>
<style scoped lang="scss">

</style>
